package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet("/userBrowsedArticle")
public class UserBrowsedArticle extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置CORS响应头
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        // 从请求体中获取JSON数据
        try {
            // 从请求体中获取JSON数据
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String json = sb.toString();

            // 解析JSON数据
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> data = objectMapper.readValue(json, Map.class);
            String writer = data.get("writer");
            String title = data.get("title");
            String category = data.get("category");
            String currentUsername = data.get("currentUsername");

            // 调用业务逻辑层的方法处理浏览文章的记录
            String result = UserService.recordArticleBrowse(writer, category,title, currentUsername);

            // 返回响应
            out.print("{\"success\": true, \"message\": \"" + result + "\"}");
            response.setStatus(HttpServletResponse.SC_OK);

        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\": false, \"message\": \"服务器内部错误\"}");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        // 设置CORS响应头
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
